package com.kotlin.android.simple.simple

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.kotlin.android.api.bean.SeatBanner
import com.kotlin.android.api.repository.SimpleRepository
import com.kotlin.android.api.base.BaseUIModel
import com.kotlin.android.core.BaseViewModel
import com.kotlin.android.api.base.checkResult
import com.kotlin.android.ktx.ext.e
import kotlinx.coroutines.launch

/**
 *
 * Created on 2020/4/24.
 *
 * @author o.s
 */
class SimpleViewModel : BaseViewModel() {
    private val repo by lazy { SimpleRepository() }

    private val _uiState = MutableLiveData<SimpleUIModel>()

    val uiState: LiveData<SimpleUIModel> = _uiState

    fun loadData() {
        viewModelScope.launch(main) {
            // 1、显示进度条
            emitUIState(showLoading = true)
            // 2、IO任务线程加载网络数据【协程同步挂起等待返回结果】
            val result = withOnIO {
                repo.loadData()
            }
            result.e()

            /*****************************************************
             * 如果有某些不需要处理的部分，不实现即可。
             * 如：提示语接口不需要关心错误页面，可不实现 [error = {}]
             *****************************************************/

            // 3、检验结果，可根据各自接口业务要求，定制合适的检验策略
            checkResult(result, error = {
                emitUIState(error = it)
            }, netError = {
                emitUIState(netError = it)
            }, needLogin = {
                emitUIState(needLogin = true)
            }, success = {
                emitUIState(success = it)
            })
        }
    }

    /**
     * 发出UI状态
     */
    private fun emitUIState(
        showLoading: Boolean = false,
        isRefresh: Boolean = false,
        loadMore: Boolean = false,
        needLogin: Boolean = false,
        error: String? = null,
        netError: String? = null,
        isEmpty: Boolean = false,
        success: SeatBanner? = null
    ) {
        val model = SimpleUIModel()
        model.showLoading = showLoading
        model.isRefresh = isRefresh
        model.loadMore = loadMore
        model.needLogin = needLogin
        model.error = error
        model.netError = netError
        model.isEmpty = isEmpty
        model.success = success

        _uiState.value = model
    }

    /**
     * 根据实际的接口业务要求，定制（增加）该对象的字段属性：
     */
    class SimpleUIModel : BaseUIModel<SeatBanner>()
}